package com.spring.boot.core.command;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

public class CommandManager {
	private static final Logger log = LoggerFactory.getLogger(CommandManager.class);

	private static final Comparator<Command.Executor> comparator = (x, y) -> Integer.compare(x.getPriority(), y.getPriority());

	private static HashMap<String, List<Command.Executor>> executors = Maps.newHashMap();

	public static synchronized void registerExecutor(String command, Command.Executor executor) {
		List<Command.Executor> executorList = executors.get(command);
		if (executorList == null) {
			executorList = Lists.newArrayList();
			executors.put(command, executorList);
		}
		executorList.add(executor);
		if (executorList.size() > 1) {
			Collections.sort(executorList, comparator);
		}
	}

	public static synchronized void removeExecutor(String command, Command.Executor executor) {
		List<Command.Executor> executorList = executors.get(command);
		if (executorList != null) {
			executorList.remove(executor);
		}
	}

	public static synchronized void removeExecutors(String command) {
		executors.remove(command);
	}

	public static synchronized void removeAllExecutor() {
		executors.clear();
	}

	public static String command(Command command) {
		log.info("Exec command: " + command.name);
		List<Command.Executor> executorList = executors.get(command.name);
		if (executorList != null) {
			StringBuffer ret = new StringBuffer();
			for (Command.Executor executor : executorList) {
				ret.append(executor.exec(command) + "\n");
			}
			return ret.toString();
		} else {
			return "Not command name!";
		}
	}
}
